package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Comment;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;


@Service(version = "1.0.0")
@Slf4j
@SuppressWarnings("all")
public class LikeQuanZiApiImpl implements LikeQuanZiApi{

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PublicQuanZiImpl publicQuanZiImpl;


    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //1.判断该用户是否已经点赞，如果已经点赞就直接返回
        if (queryUserIsLike(userId, publishId)) {
            return false;
        }

        //保存Comment数据
        Boolean result = publicQuanZiImpl.saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result) {
            return false;
        }

        //修改redis中的点赞数以及是否点赞
        //修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }


    /**
     * 查询用户是否点赞该动态
     *
     * @param userId
     * @param publishId
     * @return
     */
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = getCommentRedisKeyPrefix(publishId);
        Object userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);

        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE));
        long count = mongoTemplate.count(query, Comment.class);

        if (count == 0) {
            return false;
        }

        //写入到redis中
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
        return true;
    }



    /**
     * 取消点赞
     *
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {

        //判断用户是否已经点赞，如果没有点赞就返回
        if (!queryUserIsLike(userId, publishId)) {
            return false;
        }

        //删除评论数据
        Boolean result = removeComment(userId, publishId, CommentType.LIKE);
        if (!result){
            return false;
        }

        //修改Redis中的数据
        //修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey =CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);

        //用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey,userHashKey);

        return true;
    }


    /**
     * 查询点赞数
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryLikeCount(String publishId) {
        //从Redis中命中查询，如果命中直接返回即可
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);

        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        //查询Mongodb
        Long count = queryCommentCount(publishId, CommentType.LIKE);
        //写入redis
        redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }




    /**
     * 查询数量
     *
     * @param publishId
     * @param commentType
     * @return
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType));
        long count = mongoTemplate.count(query, Comment.class);
        return count;
    }


    /**
     * 删除评论数据
     *
     * @param userId
     * @param publishId
     * @param commentType
     * @return
     */
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType()));
        long deletedCount = mongoTemplate.remove(query, Comment.class).getDeletedCount();

        return deletedCount > 0;
    }
}
